<?php
/**
 * Created by PhpStorm.
 * User: RUNFA
 * Date: 2015/9/5
 * Time: 15:36
 */

namespace Admin\Controller;

use Think\Page;
use Think\Think;

class AttachmentController extends BaseController
{

	public function index(){
		echo 'no data';
		exit;
	}

	/**
	 * 上传文件操作function
	 */
	public function uploadFiles(){
		
		//异步加载数据标识
		$is_ajax = I('request.is_ajax');
		if(!empty($is_ajax)){
			//只显示图片
			$extension_array =  array('jpg','gif','png','jpeg');
			$where['file_extension_name'] =array('in',$extension_array);
			
			$cur_id = UID;
			$where['create_uid']=$cur_id;
			$where['module']=1;
			$where['shop_id']=0;
			
			$where['attachment_groupid']=1;
			$this->lists = M('attachment')->where($where)->order('id desc')->select();
			
			$this->display('picsList');
			exit;
		}
		
		$this->groups=array(
			array('id'=>1,'title'=>'未分组','module_name'=>'no_group'),
			array('id'=>2,'title'=>'产品图片','module_name'=>'goods'),
			array('id'=>3,'title'=>'系统消息','module_name'=>'system_message'),
			array('id'=>4,'title'=>'预售管理','module_name'=>'presell_manage'),
			array('id'=>5,'title'=>'文章图片','module_name'=>'article'),
			array('id'=>6,'title'=>'分类图片','module_name'=>'category'),
			array('id'=>7,'title'=>'品牌图片','module_name'=>'brand'),
			array('id'=>8,'title'=>'电脑广告','module_name'=>'pc_advertisement'),
			array('id'=>9,'title'=>'手机广告','module_name'=>'mobile_advertisement'),
		);
		
		$this->assign('module_name',I('request.module_name','no_group'));
		$this->assign('groupid',I('request.groupid',1));
		$this->assign('only_choose_one',I('request.only_choose_one'));
		$this->assign('isUploadPic',I('isUploadPic','trim'));
		$this->assign('attachment_upload',C('ATTACHMENT_UPLOAD'));
//         $this->groups=M('attachment_group')->select();
		$this->display();
	}


	/**
	 * 查阅不同模块的文件列表
	 */
	public function loaddingFileListByType(){
		
		$page = isset($_REQUEST['page'])?intval($_REQUEST['page']):1;
		$rows = 36;
		
		//分组id
		$groupid = I('request.groupid',0,'intval');
		//组名称
		$module_name = I('request.module_name','','trim');
		//只显示图片的模块 组
		$isUploadPic = I('request.isUploadPic',0,'intval');
		$group_pic_array = array(2,3,4,5);
		if( in_array($groupid, $group_pic_array) || !empty($isUploadPic) ){
			//只显示图片
			$extension_array =  array('jpg','gif','png','jpeg');
			$where['file_extension_name'] =array('in',$extension_array);
		}
		//图片名称
		$name = I('request.name','','trim');
		if(!empty($name)){
			$where['attachment_name']=array('like',"%{$name}%");
		}
		
		$cur_id = UID;
		// $where['create_uid']=$cur_id;
		$where['module']=$module_name;
		$where['data_id']=0;
		//         $where['attachment_groupid']=$groupid;
		
		
		$count = M('attachment')->where($where)->order('id desc')->count();//总条数		
		$total_page = ceil($count/$rows);//总页数
		$is_all = 0;
		if($total_page <= $page)$is_all=1;
		
		$limit = (($page-1)*$rows).','.$rows;		
		

		$lists = M('attachment')->where($where)->order('id desc')->limit($limit)->select();
		$attachment_upload = C('ATTACHMENT_UPLOAD');
		foreach ($lists as $key =>$val){
			$file_img_path = $attachment_upload["rootPath"].'/'.$val['file_name'];
			if( !file_exists('.'.$file_img_path) ){
				$file_img_path = $attachment_upload["orginPath"].'/'.$val['file_name'];
			}
			$lists[$key]['org_file_name'] = $attachment_upload["orginPath"].'/'.$val['file_name'];
			$lists[$key]['file_path']=$file_img_path;
		}
		
		echo json_encode(array('lists'=>$lists,'count'=>count($lists),'is_all'=>$is_all));
		exit;
		
	}

	/**
	 * 修改文件data-id
	 */
	public function updateFileStatus(){
		$id = I('id');
		M('attachment')->where(array('id'=>$id))->setField('data_id',0);
		echo json_encode(array('status'=>1));
		exit;
	}

    /**
     * 添加分组
     */
    public function addGroup(){
       if(IS_POST){
           $model= M("attachment_group");
           $model->create();
           if($model->add()){
               $exe_scriptstr = "<script>
                setTimeout(function(){
                var win=    art.dialog.opener;
                            win._page_load_userlist_datalist();
                            art.dialog.close();
                },2000);

           </script>";
               //添加成功后，输出文本，把js脚本一起输出，前台只要html到某个div里就能够执行js
               $this->success('添加成功！' . $exe_scriptstr);
           }else{
               $this->error("添加失败！");
           }
       }else{
           $this->display();
       }
    }

    public  function updateGroup(){
        if(IS_POST){
            $model= M("attachment_group");
            $data["title"]=I("request.title");
            $data["sort"]=intval(I("request.sort"));
            $data['id']=intval(I("request.id"));
            if($model->data($data)->where(array("id"=>$data["id"]))->save()){
                $exe_scriptstr = "<script>
                setTimeout(function(){
                var win=    art.dialog.opener;
                            win._page_load_userlist_datalist();
                            art.dialog.close();
                },2000);
           </script>";
                //添加成功后，输出文本，把js脚本一起输出，前台只要html到某个div里就能够执行js
                $this->success('修改成功！' . $exe_scriptstr);
            }else {
                $this->error('修改失败！');
            }
        }else{
            $model= M("attachment_group");
            $this->m=$model->where(array("id"=>intval(I("request.id"))))->find();
            $this->display();
        }

    }

    /**
     * 删除图片
     */
    public function delPics(){
        $pic_id=I('id','','trim');

        $pic_id=rtrim($pic_id,',');
        //读取系统配置
        $a_u = C('ATTACHMENT_UPLOAD');

        //确定
        $is_confirm = I('is_confirm',0,'intval');

        if(empty($pic_id)){
            $this->error('参数错误');
            exit;
        }

        $_attachment = M('attachment');

        //强制删除
        if(!empty($is_confirm)){
            //图片列表
            $attachment_pic_list= $_attachment ->where(array('id'=>array('in',$pic_id)))
                ->field(" file_name ")->select();

            $r = M('attachment')->where(array('id'=>array('in',$pic_id)))->delete();
            if($r){
				$goods_gallery = M('goods_gallery');
                foreach($attachment_pic_list as $v){
                	//循环上传图片和商品关联记录
                	//删除产品关联表记录
                	$goods_gallery->where(array('thumb_url'=>$v['file_name']))->delete();
                    //循环删除图片
                    @unlink('./'.$a_u['orginPath'].'/'.$v['file_name']);
                    @unlink('./'.$a_u['rootPath'].'/'.$v['file_name']);
                }

                echo json_encode(array('status'=>1,'info'=>'操作成功'));
                exit;
            }else{
                echo json_encode(array('status'=>0,'info'=>'操作失败'));
                exit;
            }
            exit;
        }

        $pic_product_count = M('goods')->alias('pro')
//          ->where(array('pro.first_img_name'=>array('in',$attachment_pic_list)))
//            ->join(CTN('attachment').' as atta on (CONCAT(atta.file_name,".",atta.file_extension_name)) = pro.first_img_name ')
//             ->join(CTN('goods_gallery').' as gg on pi.goods_id = pro.goods_id ')
            ->join(CTN('attachment').' as atta on pro.goods_img = (CONCAT("attas/",atta.file_name)) ')
            ->where(array('atta.id'=>array('in',$pic_id),'pro.is_general'=>1))
            ->field(' pro.goods_name as product_name, pro.goods_englishname,atta.attachment_name as file_name,atta.id as atta_id')
            ->order('atta.id')
            ->select();


        if(count($pic_product_count)>0){
            echo json_encode(array('status'=>-1,'info'=>'图片已被产品使用不能删除!','data'=>$pic_product_count));
            exit;
        }

        //图片列表
        $attachment_pic_list= $_attachment ->where(array('id'=>array('in',$pic_id)))
            ->field(" file_name ")->select();
        
        $r = M('attachment')->where(array('id'=>array('in',$pic_id)))->delete();
        if($r){
            foreach($attachment_pic_list as $v){
                //循环删除图片
                @unlink('./'.$a_u['orginPath'].'/'.$v['file_name']);
                @unlink('./'.$a_u['rootPath'].'/'.$v['file_name']);
            }

            echo json_encode(array('status'=>1,'info'=>'操作成功'));
            exit;
        }else{
            echo json_encode(array('status'=>0,'info'=>'操作失败'));
            exit;
        }

    }
    
    
	/* 上传图片 uploadFile*/
	/**
     * 附件上传
     * @author nirunfa write by 2015-09-05
     */
    public function uploadFile(){
		//TODO: 用户登录检测

	    /* 返回标准数据 */
	    $return  = array('status' => 1, 'info' => '上传成功', 'data' => '');

	    //模块名称
	    $module_name =I('module_name','','trim');
	    //组id
	    $groupid = I('request.groupid');
	    //原始模块名称
	    $org_module_name = I('request.org_module_name','','trim');
	
	    /* 调用文件上传组件上传文件 */
	    $Attachment = D('Attachment');
	    $pic_driver = C('ATTACHMENT_UPLOAD_DRIVER');
	    //设置模块名称数据，用于添加数据
	    $settings=C('ATTACHMENT_UPLOAD');
	    //后台默认模块 1
	    $settings['module']=$module_name;
	    //只能上传图片的组
	    $isUploadPic =I('isUploadPic');
	    $group_pic_array = array(2,3,4,5);
		if( in_array($groupid, $group_pic_array) || !empty($isUploadPic) ){
			$settings['exts']='jpg,gif,png,jpeg';
	    }
	    
	    $settings['org_module_name']=$org_module_name;

	    $info = $Attachment->upload(
		    $_FILES,
		    $settings,
		    C('ATTACHMENT_UPLOAD_DRIVER'),
		    C("UPLOAD_{$pic_driver}_CONFIG"),
            I("request.groupid")
	    ); //TODO:上传到远程服务器

	    /* 记录图片信息 */
	    if($info){
		    $return['status'] = 1;
		    $return = array_merge($info['download'], $return);
		    $return['num']=$_GET['num'];
		    
		    //处理图片信息
		    $file_img_path = $settings["rootPath"].'/'.$return['file_name'];
		    if( !file_exists('.'.$file_img_path) ){
		    	$file_img_path = $settings["orginPath"].'/'.$return['file_name'];
		    }
		    $return['org_file_name'] = $settings["orginPath"].'/'.$return['file_name'];
		    $return['file_path']=$file_img_path;	
	    } else {
		    $return['status'] = 0;
		    $return['info']   = $Attachment->getError();
	    }

	    /* 返回JSON数据 */
	    $this->ajaxReturn($return);
    }
    
    
    /* 上传视频 */
    public function uploadVideo(){
    	//原始图片
    	$orgimg = I('request.orgimg');
    	
    	$return  = array('status' => 1, 'info' => '上传成功', 'data' => '');
    	/* 调用文件上传组件上传文件 */
    	$File = D('GoodsVideo');
    	$file_driver = C('VIDEO_UPLOAD');
    	$info = $File->uploadVideo(
    			$_FILES,
    			C('VIDEO_UPLOAD'),
    			C('VIDEO_UPLOAD_DRIVER'),
    			C("UPLOAD_{$file_driver}_CONFIG")
    	);
    
    	/* 记录附件信息 */
    	if($info){
    		$return['data'] =$info; 
    		
    		//这里需要删除原先上传的文件  
    		if( !empty($orgimg) ){
    			@unlink('./attas/videos/'.$orgimg);
    		}
    	} else {
    		$return['status'] = 0;
    		$return['info']   = $File->getError();
    	}
    
    	/* 返回JSON数据 */
    	$this->ajaxReturn($return);
    }

}